package org.finesys.common.redisson.service.impl;

import lombok.RequiredArgsConstructor;
import org.finesys.common.redisson.constants.RedissonLockType;
import org.finesys.common.redisson.entity.LockEntity;
import org.finesys.common.redisson.service.RedissonService;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

/**
 * 联锁
 */
@RequiredArgsConstructor
public class RedissonMultiLockServiceImpl implements RedissonService {

    private final RedissonClient redissonClient;

    @Override
    public boolean lock(LockEntity lockEntity) {
        //获取锁
        RLock[] rLocks = lockEntity.getKeyList().stream().map(redissonClient::getLock).toArray(RLock[]::new);
        //创建连锁对象
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(rLocks);
        //枷锁
        try {
            return redissonMultiLock.tryLock(lockEntity.getWaitTime(), lockEntity.getLeaseTime(), lockEntity.getTimeUnit());
        } catch (InterruptedException e) {
            return false;
        }
    }

    @Override
    public void unlock(LockEntity lockEntity) {
        //获取锁
        RLock[] rLocks = lockEntity.getKeyList().stream().map(redissonClient::getLock).toArray(RLock[]::new);
        //创建连锁对象
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(rLocks);
        //解锁
        redissonMultiLock.unlockAsync();
    }

    @Override
    public RedissonLockType lockType() {
        return RedissonLockType.MULTI;
    }
}
